//
//  LoanEnquiryViewController.m
//  Rong360
//
//  Created by tianliwei on 6/2/14.
//  Copyright (c) 2014 tianliwei. All rights reserved.
//

#import "LoanEnquiryViewController.h"
#import "AttributedLabel.h"
#import "EnquiryDKCPCell.h"
#import "EnquiryXYDCell.h"
#import "EnquiryXYKCell.h"
#import "ProductEntity.h"
#import "WebViewController.h"
#import "APService.h"
#import "CityListViewController.h"
#import <CoreText/CoreText.h>
@interface LoanEnquiryViewController ()
@property (nonatomic, strong)UIActivityIndicatorView *webLoading;

@end

static NSString *DKCPCell = @"DKCPCell";
static NSString *XYDCell = @"XYDCell";
static NSString *XYKCell = @"XYKCell";


@implementation LoanEnquiryViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"贷款查询" image:nil tag:0];
        [[self tabBarItem] setFinishedSelectedImage:[UIImage imageNamed:@"tab_3_focus"] withFinishedUnselectedImage:[UIImage imageNamed:@"tab_3"]];
        [[self tabBarItem] setTitleTextAttributes:@{UITextAttributeTextColor: [UIColor grayColor],
                                                    UITextAttributeFont:[UIFont systemFontOfSize:kTabBarFontSize]
                                                    } forState:UIControlStateNormal];
        [[self tabBarItem] setTitleTextAttributes:@{UITextAttributeTextColor: RGBCOLOR(0, 172, 246),
                                                    UITextAttributeFont:[UIFont systemFontOfSize:kTabBarFontSize]
                                                    } forState:UIControlStateSelected];
    }
    return self;
}

- (void)showTableView:(NSNotification *)noti{
    [self.webLoading removeFromSuperview];
    if (!self.tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_NAVIFRAME_HEIGHT) style:UITableViewStyleGrouped];
        if (!IOS7_OR_LATER) {
            self.tableView.frame = CGRectMake(-10, 0, UI_SCREEN_WIDTH + 20, UI_NAVIFRAME_HEIGHT);
        }
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.backgroundView = nil;
        [self.tableView registerNib:[UINib nibWithNibName:@"EnquiryDKCPCell" bundle:nil] forCellReuseIdentifier:DKCPCell];
        [self.tableView registerNib:[UINib nibWithNibName:@"EnquiryXYKCell" bundle:nil] forCellReuseIdentifier:XYKCell];
        [self.tableView registerNib:[UINib nibWithNibName:@"EnquiryXYDCell" bundle:nil] forCellReuseIdentifier:XYDCell];
        [self.view addSubview:self.tableView];
    }
    [self.tableView reloadData];

}

- (void)presentCityViewController{
    CityListViewController *cityVC = [[CityListViewController alloc]init];
    cityVC.delegate = self;
    cityVC.dismissStyle = LoanEnquiry;
    UINavigationController *naviVC = [[UINavigationController alloc]initWithRootViewController:cityVC];
    [self presentModalViewController:naviVC animated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    NSString *currentCity = [[NSUserDefaults standardUserDefaults]objectForKey:kCurrentCity];
    UIButton *cityButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cityButton setBackgroundColor:[UIColor clearColor]];
    [cityButton setTitle:currentCity forState:UIControlStateNormal];
    [cityButton addTarget:self action:@selector(presentCityViewController) forControlEvents:UIControlEventTouchUpInside];
    cityButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    cityButton.frame = CGRectMake(0.0f, 0.0f, 80.0f, 25.0f);
    UIBarButtonItem *cityButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cityButton];
    self.navigationItem.rightBarButtonItem = cityButtonItem;
    [self.tableView reloadData];
}


- (void) citySelectionUpdate:(NSString*)selectedCity selectedCityID:(NSString *)selectedCityID{
    
    UIButton *button = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
    [button setTitle:selectedCity forState:UIControlStateNormal];
    if (selectedCity) {
        [APService setTags:[NSSet setWithObject:selectedCity] callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
    }
    [[NSUserDefaults standardUserDefaults]setObject:selectedCityID forKey:kCurrentCityID];
    [[NSUserDefaults standardUserDefaults]setObject:selectedCity forKey:kCurrentCity];
    NSString *productPara = [NSString stringWithFormat:@"city_id=%@",selectedCityID];
    NSString *productUrl = [NSString stringWithFormat:@"%@?%@&token=%@",ProductUrl,productPara,[SignUtil stringFromURL:productPara]];
    NSLog(@"productUrl:======> %@\n",productUrl);
    [RequestUtil requestWithType:Product Url:productUrl];
    self.webLoading = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.webLoading.frame = CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_NAVIFRAME_HEIGHT);
    [self.webLoading startAnimating];
    [self.view addSubview:self.webLoading];
    
}

- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.title = @"贷款查询";
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showTableView:) name:kGetProductSuccess object:nil];
    
    NSString *cityID = [[NSUserDefaults standardUserDefaults]objectForKey:kCurrentCityID];
    
    if (cityID) {
        NSString *productPara = [NSString stringWithFormat:@"city_id=%@",cityID];
        NSString *productUrl = [NSString stringWithFormat:@"%@?%@&token=%@",ProductUrl,productPara,[SignUtil stringFromURL:productPara]];
        NSLog(@"productUrl:======> %@\n",productUrl);
        [RequestUtil requestWithType:Product Url:productUrl];
        
        self.webLoading = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        self.webLoading.frame = CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_NAVIFRAME_HEIGHT);
        [self.webLoading startAnimating];
        [self.view addSubview:self.webLoading];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 60;
    }else if (section == 1){
        return 80;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 3) {
            return 73;
        }
        return 53;
        
    }else if(indexPath.section == 1) {
        if (indexPath.row == 2) {
            return 100;
        }else if(indexPath.row == 1){
            return 40;
        }else if(indexPath.row == 3){
            return 70;
        }else{
            return 52;
        }
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = nil;
    switch (section) {
        case 0:{
            view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 60)];
            view.backgroundColor = [UIColor whiteColor];
            AttributedLabel *subLabel = [[AttributedLabel alloc]initWithFrame:CGRectMake(IOS7_OR_LATER?10:20, 37, 310, 12)];
            NSString *currentCity = [[NSUserDefaults standardUserDefaults]objectForKey:kCurrentCity];
            //必须先转化成整数，然后重新转化为字符串 没明白 谁明白了给我发邮件吧，多谢 lw_tian@163.com (田立伟)
            NSString *pNum = [ProductEntity sharedProduct].p_num;
            NSString *p_Num = [NSString stringWithFormat:@"%d",[pNum intValue]];
            NSString *str = [NSString stringWithFormat:@"%@共有%@家银行提供房贷, 最低利率%@, %@家提供",currentCity,p_Num,[ProductEntity sharedProduct].minRateValue,[ProductEntity sharedProduct].minRateNum];
            subLabel.text = str;
            [subLabel setFont:[UIFont systemFontOfSize:11]fromIndex:0 length:str.length];
            [subLabel setColor:[UIColor redColor] fromIndex:(2+currentCity.length) length:p_Num.length];
            NSString *minRateValue = [ProductEntity sharedProduct].minRateValue;
            NSString *minRate = [NSString stringWithFormat:@"%d",[minRateValue intValue]];
            [subLabel setColor:[UIColor redColor] fromIndex:(2+currentCity.length+p_Num.length+13) length:minRate.length];
            
            NSString *minRateNum = [ProductEntity sharedProduct].minRateNum;
            NSString *minNum = [NSString stringWithFormat:@"%d",[minRateNum intValue]];
            [subLabel setColor:[UIColor redColor] fromIndex:(2+currentCity.length+p_Num.length+13+minRate.length+3) length:minNum.length];
            [view addSubview:subLabel];
            
            UILabel *mainLabel = [[UILabel alloc]initWithFrame:CGRectMake(IOS7_OR_LATER?10:20, 10, 100, 25)];
            mainLabel.font = [UIFont fontWithName:@"Arial-BoldMt" size:18];
            mainLabel.text = @"贷款产品";
            [view addSubview:mainLabel];
            break;
        }
        case 1:{
            view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 75)];
            view.backgroundColor = [UIColor whiteColor];
            UILabel *mainLabel = [[UILabel alloc]initWithFrame:CGRectMake(IOS7_OR_LATER?10:20, 10, 100, 25)];
            mainLabel.font = [UIFont fontWithName:@"Arial-BoldMt" size:18];
            UILabel *subLabel = [[UILabel alloc]initWithFrame:CGRectMake(IOS7_OR_LATER?10:20, 32, 310, 20)];
            subLabel.font = [UIFont fontWithName:@"Arial-BoldMt" size:12];
            UILabel *xinyongLabel = [[UILabel alloc]initWithFrame:CGRectMake(IOS7_OR_LATER?10:20, 58, 310, 20)];
            xinyongLabel.font = [UIFont fontWithName:@"Arial-BoldMt" size:14];
            [view addSubview:mainLabel];
            [view addSubview:subLabel];
            [view addSubview:xinyongLabel];
            mainLabel.text = @"首付不够";
            subLabel.text = @"您可以选择一些低息信用贷款和大额信用卡来补充首付";
            subLabel.font = [UIFont systemFontOfSize:10];
            subLabel.textColor = [UIColor lightGrayColor];
            xinyongLabel.text = @"信用贷";
            xinyongLabel.font = [UIFont systemFontOfSize:13];
            break;
        }
        default:
            break;
    }
    return view;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    switch (section) {
        case 0:
            return 4;
        case 1:
            return 4;
        default:
            break;
    }
    return 0;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:{
            switch (indexPath.row) {
                case 0:
                case 1:
                case 2:{
                    EnquiryDKCPCell *cell = [tableView dequeueReusableCellWithIdentifier:DKCPCell];
                    cell.backgroundView = [[UIView alloc]init];
                    cell.backgroundColor = [UIColor whiteColor];
                    NSDictionary *dic = [ProductEntity sharedProduct].banks[indexPath.row];
                    BankUnit *bankUnit = [[BankUnit alloc]init];
                    [bankUnit parseFromDic:dic];
                    NSString *bankStr = [NSString stringWithFormat:@"%@ 最低%@",bankUnit.bank_name,bankUnit.rate];
                    [cell.thumbImg setImageWithURL:[NSURL URLWithString:bankUnit.logo]];
                    cell.mainLabel.text = bankStr;
                    return cell;
                }
                case 3:{
                    static NSString *identifyCell1 = @"Cell1";
                    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifyCell1];
                    if (!cell) {
                        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifyCell1];
                        cell.backgroundView = [[UIView alloc]init];
                        cell.backgroundColor = [UIColor whiteColor];
                        cell.selectionStyle = UITableViewCellSelectionStyleNone;
                        UIButton *button = [UIButton buttonWithTag:0 frame:CGRectMake(10, 0, 300, 50) title:@"查看全部银行" fontSize:18 color:[UIColor whiteColor] target:self action:@selector(buttonClicked:)];
                        [button setBackgroundImage:[UIImage imageNamed:@"btn_green_normal"] forState:UIControlStateNormal];
                        [button setBackgroundImage:[UIImage imageNamed:@"btn_green_focus"] forState:UIControlStateHighlighted];
                        [cell.contentView addSubview:button];
                    }
                    return cell;
                }
                default:
                    break;
            }
            break;
        }
        case 1:{
            switch (indexPath.row) {
                case 0:{
                    EnquiryXYDCell *cell = [tableView dequeueReusableCellWithIdentifier:XYDCell];
                    cell.backgroundView = [[UIView alloc]init];
                    cell.backgroundColor = [UIColor whiteColor];
                    if ([ProductEntity sharedProduct].xyds && [ProductEntity sharedProduct].xyds.count) {
                        NSDictionary *dic = [ProductEntity sharedProduct].xyds[indexPath.row];
                        XYDUnit *xydUnit = [[XYDUnit alloc]init];
                        [xydUnit parseFromDic:dic];
                        
                        [cell.thumbImg setImageWithURL:[NSURL URLWithString:xydUnit.logo]];
                        cell.mainLabel.text = xydUnit.name;
                        cell.subLabel.text = xydUnit.feature;
                    }else{
                        cell.mainLabel.text = @"暂无推荐产品";
                        cell.subLabel.text = @"如有合适的贷款产品我们会第一时间更新";
                    }
                    
                    return cell;
                }
                case 1:{
                    static NSString *identifyCell2 = @"Cell2";
                    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifyCell2];
                    if (!cell) {
                        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifyCell2];
                        cell.backgroundView = [[UIView alloc]init];
                        cell.backgroundColor = [UIColor whiteColor];
                        cell.accessoryType = UITableViewCellAccessoryNone;
                        UIButton *xydButton = [UIButton buttonWithTag:1 frame:CGRectMake(10, 2, 300, 38) normalImage:[UIImage imageNamed:@"btn_grey_normal"] highlightedImage:[UIImage imageNamed:@"btn_grey_focus"] target:self action:@selector(buttonClicked:)];
                        [xydButton setTitle:@"查看全部产品" forState:UIControlStateNormal];
                        xydButton.titleLabel.font = [UIFont systemFontOfSize: 14.0];
                        [xydButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -190, 0, 0)];
                        [xydButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                        [cell.contentView addSubview:xydButton];
                    }
                    return cell;
                }
                case 2:{
                    EnquiryXYKCell *cell = [tableView dequeueReusableCellWithIdentifier:XYKCell];
                    for (id v in cell.contentView.subviews) {
                        if ([v isKindOfClass:[UIButton class]]) {
                            UIButton *btn = (UIButton *)v;
                            [btn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
                        }
                    }
                    cell.backgroundView = [[UIView alloc]init];
                    cell.backgroundColor = [UIColor whiteColor];
                    NSArray *xykArr = [ProductEntity sharedProduct].xyks;
                    XYKUnit *xykUnit = [[XYKUnit alloc]init];
                    [xykUnit parseFromDic:xykArr[0]];
                    [cell.img1 setImageWithURL:[NSURL URLWithString:xykUnit.logo]];
                    [cell.name1 setText:xykUnit.name];
                    [xykUnit parseFromDic:xykArr[1]];
                    [cell.img2 setImageWithURL:[NSURL URLWithString:xykUnit.logo]];
                    [cell.name2 setText:xykUnit.name];
                    [xykUnit parseFromDic:xykArr[2]];
                    [cell.img3 setImageWithURL:[NSURL URLWithString:xykUnit.logo]];
                    [cell.name3 setText:xykUnit.name];
                    [xykUnit parseFromDic:xykArr[3]];
                    [cell.img4 setImageWithURL:[NSURL URLWithString:xykUnit.logo]];
                    [cell.name4 setText:xykUnit.name];
                    [xykUnit parseFromDic:xykArr[4]];
                    [cell.img5 setImageWithURL:[NSURL URLWithString:xykUnit.logo]];
                    [cell.name5 setText:xykUnit.name];
                    return cell;
                }
                case 3:{
                    static NSString *identifyCell3 = @"Cell3";
                    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifyCell3];
                    if (!cell) {
                        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifyCell3];
                        cell.backgroundView = [[UIView alloc]init];
                        cell.backgroundColor = [UIColor whiteColor];
                        UIButton *xykButton = [UIButton buttonWithTag:2 frame:CGRectMake(10, 0, 300, 38) normalImage:[UIImage imageNamed:@"btn_grey_normal"] highlightedImage:[UIImage imageNamed:@"btn_grey_focus"] target:self action:@selector(buttonClicked:)];
                        [xykButton setTitle:@"查看全部信用卡" forState:UIControlStateNormal];
                        xykButton.titleLabel.font = [UIFont systemFontOfSize: 14.0];
                        [xykButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -176, 0, 0)];
                        [xykButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                        [cell.contentView addSubview:xykButton];
                    }
                    return cell;
                }
                default:
                    break;
            }
            break;
        }
        default:
            break;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *normalCell = [tableView cellForRowAtIndexPath:indexPath];
    if ([normalCell isMemberOfClass:[UITableViewCell class]]) {
        return;
    }
    NSString *url = nil;
    NSString *title = nil;
    switch (indexPath.section) {
        case 0:{
            NSDictionary *dic = [ProductEntity sharedProduct].banks[indexPath.row];
            BankUnit *bankUnit = [[BankUnit alloc]init];
            [bankUnit parseFromDic:dic];
            url = bankUnit.url;
            title = bankUnit.name;
            break;
        }
        case 1:{
            switch (indexPath.row) {
                case 0:{
                    if ([ProductEntity sharedProduct].xyds && [ProductEntity sharedProduct].xyds.count) {
                        NSDictionary *dic = [ProductEntity sharedProduct].xyds[indexPath.row];
                        XYDUnit *xydUnit = [[XYDUnit alloc]init];
                        [xydUnit parseFromDic:dic];
                        url = xydUnit.url;
                        title = xydUnit.name;
                    }else{
                        url = @"http://m.rong360.com/#/cityNavi/";
                        title = @"";
                    }
                    
                    break;
                }
                default:
                    break;
            }
        }
        default:
            break;
    }
    self.hidesBottomBarWhenPushed = YES;

    WebViewController *webVC = [[WebViewController alloc]initWithUrl:url title:title];
    [self.navigationController pushViewController:webVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    
}


- (void)buttonClicked:(UIButton *)sender{
    NSString *url;
    NSString *title = nil;
    switch (sender.tag) {
        case 0:{
            url = [ProductEntity sharedProduct].morebankUrl;
            title = @"查看全部银行";
            break;
        }
        case 1:{
            url = [ProductEntity sharedProduct].moreXYDUrl;
            title = @"查看全部产品";
            break;
        }
        case 2:{
            url = [ProductEntity sharedProduct].moreXYKUrl;
            title = @"查看全部信用卡";
            break;
        }
        case 11:{
            NSDictionary *dic = [ProductEntity sharedProduct].xyks[0];
            XYKUnit *xykUnit = [[XYKUnit alloc]init];
            [xykUnit parseFromDic:dic];
            url = xykUnit.url;
            title = xykUnit.name;
            break;
        }
        case 12:{
            NSDictionary *dic = [ProductEntity sharedProduct].xyks[1];
            XYKUnit *xykUnit = [[XYKUnit alloc]init];
            [xykUnit parseFromDic:dic];
            url = xykUnit.url;
            title = xykUnit.name;
            break;
        }
        case 13:{
            NSDictionary *dic = [ProductEntity sharedProduct].xyks[2];
            XYKUnit *xykUnit = [[XYKUnit alloc]init];
            [xykUnit parseFromDic:dic];
            url = xykUnit.url;
            title = xykUnit.name;
            break;
        }
        case 14:{
            NSDictionary *dic = [ProductEntity sharedProduct].xyks[3];
            XYKUnit *xykUnit = [[XYKUnit alloc]init];
            [xykUnit parseFromDic:dic];
            url = xykUnit.url;
            title = xykUnit.name;
            break;
        }
        case 15:{
            NSDictionary *dic = [ProductEntity sharedProduct].xyks[4];
            XYKUnit *xykUnit = [[XYKUnit alloc]init];
            [xykUnit parseFromDic:dic];
            url = xykUnit.url;
            title = xykUnit.name;
            break;
        }
        default:
            break;
    }
    self.hidesBottomBarWhenPushed = YES;
    WebViewController *webVC = [[WebViewController alloc]initWithUrl:url title:title];
    [self.navigationController pushViewController:webVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
